interface pingData {
    name: string;
    avatar: string;
    userId: string;
    updateTime: number;
    ping: number;
}
const Player_Ping: pingData[] = [];
function getPing(entity: GamePlayerEntity) {
    const findPing = Player_Ping.find((a) => a.userId === entity.player.userId);
    return findPing ? findPing.ping : -1;
}

function hanging(entity: GamePlayerEntity) {
    const findPing = Player_Ping.find((a) => a.userId === entity.player.userId);
    return findPing ? Date.now() - findPing.updateTime > 2000 : false;
}

function hangingFunc() {
    setInterval(() => {
        world.querySelectorAll('player').forEach((e) => {
            const findPing = Player_Ping.find(
                (a) => a.userId === e.player.userId
            );
            remoteChannel.sendClientEvent(e, {
                type: 'updateUI',
                data: {
                    ping: getPing(e),

                    userId: e.player.userId,
                    name: e.player.name,
                    serverId: world.serverId,
                    online: world.querySelectorAll('player').length,
                },
            });
            if (findPing) {
                findPing.updateTime = Date.now();
            } else {
                Player_Ping.push({
                    name: e.player.name,
                    avatar: e.player.name,
                    userId: e.player.name,
                    updateTime: Date.now(),
                    ping: -1,
                });
            }
            remoteChannel.sendClientEvent(e, {
                type: 'ping',
                data: Date.now(),
            });
        });
    }, 1000);
    remoteChannel.onServerEvent(({ entity, args }) => {
        if (args.type === 'ping') {
            const pings = Date.now() - (args.data as number);
            const findPing = Player_Ping.find(
                (a) => a.userId === entity.player.userId
            );
            if (findPing) {
                findPing.ping = pings;
            }
        }
    });
}

export { hangingFunc, hanging, getPing };
